<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示信息区域 -->
      <el-alert title="注意:" description="只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false">
      </el-alert>

      <!-- 数据操作区域 -->
      <el-row class="el-row-margin">
        <el-col>
          <span style="font-size: 14px;">请选择商品分类: </span>
          <!-- 选择商品分类的级联选择器 -->
          <el-cascader v-model="selectedCateKeys" :options="cateList" :props="cateProps" @change="handleCascaderChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- 多标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" label="详细">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <!-- 循环渲染tags: 其中key为索引即数组下标, item为每一项真实值 -->
                <el-tag :closable="true" v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>
                <!-- 键入切换输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="tagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 离开切换添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性区域 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" label="详细">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <!-- 循环渲染tags: 其中key为索引即数组下标, item为每一项真实值 -->
                <el-tag :closable="true" v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>
                <!-- 键入切换输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="tagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 离开切换添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- **静态与动态共用** 添加操作对话框 -->
    <el-dialog :title="'添加'+dialogTitle" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 添加参数对话框 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="dialogTitle+': '" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- **静态与动态共用** 修改操作对话框 -->
    <el-dialog :title="'修改'+dialogTitle" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 添加参数对话框 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="dialogTitle+': '" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定的数据
      selectedCateKeys: [],
      // 激活的页签的名称
      activeName: 'many',
      // 动态数据
      manyTableData: [],
      // 静态数据
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请在此输入名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请在此输入名称', trigger: 'blur' }
        ]
      }
      // 控制按钮和文本框切换显示, 此值会在多个框内共享, 有bug, 弃用
      // inputVisible: false,
      // 文本框输入的内容, 此值会在多个框内共享, 有bug, 弃用
      // inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  // 计算属性
  computed: {
    // 计算按钮禁用属性
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选择的三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 根据激活标签显示对话框标题
    dialogTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // this.$message.success(res.meta.msg)
      this.cateList = res.data
      // console.log(this.cateList);
    },
    // 级联选择器选中项变化触发函数
    handleCascaderChange () {
      this.getParamsData()
    },
    // 处理标签页点击事件的函数
    handleTabClick () {
      this.getParamsData()
      // console.log(this.activeName);
    },
    // 获取参数的列表数据
    async getParamsData () {
      // console.log(this.selectedCateKeys);
      // 选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        // **DEBUG** 将不可操作的项全部清空, 以防出现无数据的误操作
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        this.$message.warning('请选择三级分类, 再继续操作!')
        return
      }
      // console.log(this.selectedCateKeys);
      // 根据所选分类的id和当前所处的面板调用对应的api
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // this.$message.success(res.meta.msg)
      // **重点** 处理返回结果
      res.data.forEach(item => {
        // 将vals字符串按空格分隔成数组, 由于空串也会分隔成存有一个空串的数组, 而不是想要的空数组, 则预先应判断排除空串的值!
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制尾部新增按钮文本框的显示与隐藏
        item.inputVisible = false
        // 文本框输入的值
        item.inputValue = ''
      })
      // console.log(res.data);
      // 进行判断, 将data保存到对应的标签页中
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定, 添加参数
    addParams () {
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    async showEditDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { param: { attr_rel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // this.$message.success(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    async removeParams (attrId) {
      const confirmRes = await this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户取消了操作
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除操作')
      }
      // 执行删除业务
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 文本框失去焦点或回车键弹起时触发
    async handleInputConfirm (rowData) {
      // **优化** 在隐藏之前判断用户是否输入了无意义的空格
      if (rowData.inputValue.trim().length === 0) {
        rowData.inputValue = ''
        rowData.inputVisible = false
        return
      }
      // console.log('tag内容合法');
      // 用户输入了合法内容, 将输入的内容添加到当前data数组中, 预先处理前后的无效空格
      rowData.attr_vals.push(rowData.inputValue.trim())
      // 调用方法
      this.saveAttrVals(rowData)
      // 保存完后需要重置标签
      rowData.inputValue = ''
      rowData.inputVisible = false
    },
    // 点击按钮时切换成文本输入框
    showInput (rowData) {
      rowData.inputVisible = true
      // **重点** 让文本框自动获得焦点
      // **解析** $nextTick 方法的作用: 当页面上元素被重新渲染之后执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.tagInputRef.$refs.input.focus();
      });
    },
    // 删除对应的参数标签项
    handleTagClosed (i, rowData) {
      // splice修改原数组, 以下表示删除1项
      rowData.attr_vals.splice(i, 1)
      // 持久化数据
      this.saveAttrVals(rowData)
    },
    // 将对attr_vals的操作保存到数据库
    async saveAttrVals (rowData) {
      // 持久化数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${rowData.attr_id}`,
        {
          attr_name: rowData.attr_name,
          attr_sel: rowData.attr_sel,
          // 以空格拼接成字符串, 保证符合后台接口所需的参数类型
          attr_vals: rowData.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 标签新增和修改都是针对字符串的扩充或减少
      this.$message.success('新标签项修改成功')
    }
  }
}
</script>
<style lang="less" scoped>
.el-row-margin {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 10px;
  width: 25%;
}
.el-tag {
  margin-right: 15px;
}
.input-new-tag {
  width: 125px;
}
</style>
